<?php
/**
 * Created by PhpStorm.
 * User: dt
 * Date: 2017/2/22
 * Time: 14:51
 */

namespace app\utils;
use app\base\BaseController;
use app\services\AccountService;
use Yii;
use yii\base\Exception;

/**
 * session操作扩展
 * @package app\utils
 */
class SessionUtil {

    /**
     * 保存session信息
     * @author dt
     * @param $data
     */
    public static function save($data)
    {
        $cache = Yii::$app->cache;
        $token = md5($data['zjyUserId'].microtime());

        $cacheData = self::_saveParams($data);
        BaseController::$token = $token;
        $cache->add($token, $cacheData, Yii::$app->params['php_session_expire']);

    }

    /**
     * 用户信息赋值
     * @author dt
     * @param $data
     * @return array
     */
    private static function _saveParams($data)
    {
        $fixedParamsArr = [
            'saasTenantId' => empty($data['zjyTenantId']) ? $data['zjyUserId'] :$data['zjyTenantId'],                   //企业标识Id
            'saasTenantINum' => $data['businessNumber'],                 //企业编号
            'saasPlatformSystemNum' => '1223234',                           //平台系统编号 不能为空，暂时写死
            'saasToken' => $data['token'],                            //安全或登录标识，通信依据
            'saasOperationName' => $data['zjyLoginName'],             //操作人登录名称
            'saasPlatformFrom' => 'PC',                                     //访问来源，pc端、app端、微信端等
            'saasIdentity'=>$data['identity'],                //用户身份标识 1 企业用户或租户 2 普通用户或二级用户
        ];
        $cacheData = [
            'php_token_time_point' => time()+Yii::$app->params['defaultParams']['php_session_expire'],   //刷新php端token时间
            'java_token_time_point' => time()+Yii::$app->params['defaultParams']['java_session_expire'],   //刷新java端token时间
            'fixedParamsArr' => $fixedParamsArr,    //用户信息
        ];
        return $cacheData;
    }

    /**
     * 移除session
     * @author dt
     * @param $token
     */
    public static function remove($token)
    {
        $cache = Yii::$app->cache;
        $cache->delete($token);
    }

    /**
     * 刷新session
     * @author dt
     * @param $token
     */
    public static function refresh($token)
    {
        $cache = Yii::$app->cache;
        $session = $cache->get($token);

        //刷新php过期时间点
        if ($session['php_token_time_point'] - time() < Yii::$app->params['defaultParams']['token_auto_refresh']) {
            $phpPoint = time() + Yii::$app->params['defaultParams']['php_session_expire'];
            $cacheData = [
                'php_token_time_point' => $phpPoint,   //刷新php端token时间
                'java_token_time_point' => $session['java_token_time_point'],   //刷新java端token时间
                'fixedParamsArr' => $session['fixedParamsArr'],    //用户信息
            ];
            $cache->set($token, $cacheData, Yii::$app->params['defaultParams']['php_session_expire']);
        }

        //刷新java过期时间点
        if ($session['java_token_time_point'] - time() < Yii::$app->params['defaultParams']['token_auto_refresh']) {

            $data = [
                'tenantId' => $session['fixedParamsArr']['saasTenantId'],
                'token' => $session['fixedParamsArr']['saasToken'],
            ];
            try {
                $userData = AccountService::getInstance()->tokenOtherInfo($data);
                $cacheData = self::_saveParams($userData);
                $cache->set($token, $cacheData, Yii::$app->params['defaultParams']['php_session_expire']);
            } catch (Exception $e) {
            }
        }
    }

    /**
     * 验证session
     * @author dt
     * @param $token
     * @return bool
     */
    public static function validate($token)
    {
        //有效期和合法性验证
        $cache = Yii::$app->cache;
        if ($cache->exists($token)) {
            //刷新token时间
            self::refresh($token);
            return true;
        }

        return false;
    }

}